<script lang="ts" setup>
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import TnSwiper from '@tuniao/tnui-vue3-uniapp/components/swiper/src/swiper.vue'
import TnSticky from '@tuniao/tnui-vue3-uniapp/components/sticky/src/sticky.vue'
import TnTabs from '@tuniao/tnui-vue3-uniapp/components/tabs/src/tabs.vue'
import TnTabsItem from '@tuniao/tnui-vue3-uniapp/components/tabs/src/tabs-item.vue'
import TnNoticeBar from '@tuniao/tnui-vue3-uniapp/components/notice-bar/src/notice-bar.vue'
import TnTitle from '@tuniao/tnui-vue3-uniapp/components/title/src/title.vue'
import TnPhotoAlbum from '@tuniao/tnui-vue3-uniapp/components/photo-album/src/photo-album.vue'
import TnLazyLoad from '@tuniao/tnui-vue3-uniapp/components/lazy-load/src/lazy-load.vue'
import TnAvatar from '@tuniao/tnui-vue3-uniapp/components/avatar/src/avatar.vue'
import TnEmpty from '@tuniao/tnui-vue3-uniapp/components/empty/src/empty.vue'
import { tnNavPage } from '@tuniao/tnui-vue3-uniapp/utils'
import TnScrollList from '@tuniao/tnui-vue3-uniapp/components/scroll-list/src/scroll-list.vue'
import { useUniAppSystemRectInfo } from '@tuniao/tnui-vue3-uniapp/hooks'
import { useSubPageProvide } from './composables'
import type { NavbarRectInfo } from '@tuniao/tnui-vue3-uniapp/components/navbar'
import type { IndexPageOnLoadFunc, IndexPageOnScrollFunc } from '@/types'
import type { TnModalInstance } from '@tuniao/tnui-vue3-uniapp'
import PageContainer from '@/components/page-container/index.vue'
import AddMiniprogram from '@/components/add-miniprogram/add-miniprogram.vue'
import useZPaging from '@/uni_modules/z-paging/components/z-paging/js/hooks/useZPaging.js'
import { useScrollTransparentNavbar } from '@/hooks'
import article from '@/api/article.js'
import circlesPost from '@/api/circlesPost.js'
import system from '@/api/system.js'
import circles from '@/api/circles.js'
import { FILE_URL } from '@/api/config.js'

const paging = ref(null)
useZPaging(paging)
const instance = getCurrentInstance()
const {
  triggerElementId,
  navbarOpacity,
  init: initTransparentScroll,
  updateTargetTriggerValue,
  opacityScrollHandle,
} = useScrollTransparentNavbar(instance)
const { navBarInfo } = useUniAppSystemRectInfo()

onMounted(() => {
  initTransparentScroll()
  getAd()
  getCirclesType()
  getMessages()
  getArticleLists()
})

// 顶部导航栏初始化完成事件
const navbarInitFinishHandle = (info: NavbarRectInfo) => {
  updateTargetTriggerValue(info.height)
}

const onLoad: IndexPageOnLoadFunc = () => {
  console.log('pageA onLoad')
}
const onScroll: IndexPageOnScrollFunc = ({ top }) => {
  console.log('pageA onScroll')
  opacityScrollHandle(top)
  paging.value.updatePageScrollTop(top)
}
useSubPageProvide(0, {
  onLoad,
  onScroll,
})

const state = reactive({
  swiperData: [],
  hotCirclesData: [],
  noticeData: [],
  noticeBar: [],
  articleLists: [],
  circlesPostLists: [],
  currentTabIndex: 0,
  currentPlate: 'dynamic',
  tabsData: [
    {
      plate: 'dynamic',
      text: '动态',
    },
    {
      plate: 'usedIdle',
      text: '闲置',
    },
    {
      plate: 'organizeBureau',
      text: '组局',
    },
  ],
})

const modalRef = ref<TnModalInstance>()
// 点击通知
const clickNotice = (index: number) => {
  modalRef.value?.showModal({
    title: '公告通知',
    content: state.noticeData[index].content,
    maskClosable: true,
  })
}
const jumpMap = (
  longitude: any,
  latitude: any,
  location: any,
  poiaddress: any
) => {
  tnNavPage(
    `/pagesA/location?longitude=${longitude}&latitude=${latitude}&location=${location}&poiaddress=${poiaddress}`
  )
}
const getArticleLists = () => {
  article
    .articleLists({
      page: 1,
      page_size: 5,
    })
    .then((res) => {
      state.articleLists = res.data
    })
    .catch((err) => {
      console.log(err, 'getArticleLists')
    })
}
const getAd = () => {
  system
    .ad()
    .then((res) => {
      state.swiperData = res.data
    })
    .catch((err: any) => {
      console.log(err, 'getAd')
    })
}
const getMessages = () => {
  system
    .messages({
      type: 'home_noticebar',
    })
    .then((res) => {
      state.noticeData = res.data
      state.noticeBar = res.data.map((item: { describe: any }) => item.describe)
    })
    .catch((err: any) => {
      console.log(err, 'getMessages')
    })
}
const getCirclesType = () => {
  circles
    .circlesType({
      navigation: 1,
    })
    .then((res) => {
      state.hotCirclesData = res.data
    })
    .catch((err) => {
      console.log(err)
    })
}
// 跳转到资讯详情页
const navArticleDetail = (id: number) => {
  tnNavPage(`/articlePages/detail?id=${id}`)
}

// 跳转到圈子详情页面
const navCirclesDetailPage = (circlesId: number) => {
  tnNavPage(`/circlesPages/detail?circlesId=${circlesId}`)
}

// 跳转到帖子详情页面
const navCirclesPostDetailPage = (circlesPostId: number) => {
  tnNavPage(`/circlesPostPages/detail?circlesPostId=${circlesPostId}`)
}
const navVideoLists = (circlesPostId: number) => {
  tnNavPage(`/circlesPostPages/video?circlesPostId=${circlesPostId}`)
}
// 跳转到用户主页
const navUserHomePage = (uId: number) => {
  tnNavPage(`/pagesA/userhome?otherUserId=${uId}`)
}

// eslint-disable-next-line camelcase
const navTopicDetailPage = (topic_name: string) => {
  tnNavPage(
    // eslint-disable-next-line camelcase
    `/circlesPages/topic/detail?topicName=${topic_name}`
  )
}

const handleCirclesPlateClick = (index: number, plate: string) => {
  state.currentPlate = plate
  paging.value.reload(true)
}

const queryList = (pageNo: any, pageSize: any) => {
  circlesPost
    .homeCirclesPostLists({
      page: pageNo,
      page_size: pageSize,
      plate: state.currentPlate,
    })
    .then((res) => {
      if (res.code == 1) {
        res.data.forEach((dynamic: { attachment_type: string; attachment: any[] }) => {
          if (dynamic.attachment_type == 'image') {
            if (Array.isArray(dynamic.attachment)) {
              // 遍历 attachment 数组
              dynamic.attachment = dynamic.attachment.map((attachment: any) => {
                return `${FILE_URL}${attachment}`
              })
            }
          }
        })
        paging.value.complete(res.data)
      }
    })
    .catch((err: any) => {
      paging.value.complete(false)
    })
}
</script>

// #ifdef MP-WEIXIN
<script lang="ts">
export default {
  options: {
    // 在微信小程序中将组件节点渲染为虚拟节点，更加接近Vue组件的表现(不会出现shadow节点下再去创建元素)
    virtualHost: true,
  },
}
</script>
// #endif

<template>
  <PageContainer :placeholder-bottom="true">
    <view class="page">
      <!-- 顶部搜索区域 -->
      <TnNavbar
        fixed
        :placeholder="false"
        back-icon=""
        back-text=""
        home-icon=""
        :bottom-shadow="false"
        :bg-color="`rgba(255, 255, 255, ${navbarOpacity})`"
        @init-finish="navbarInitFinishHandle"
      >
        <view class="navbar">
          <view
            class="search-box"
            :style="{
              backgroundColor: `rgba(248, 247, 248 , ${Math.max(
                0.25,
                navbarOpacity
              )})`,
              color: `rgba(0, 0, 0 , ${Math.max(0.45, navbarOpacity)})`,
            }"
            @tap.stop="tnNavPage('/pagesA/search')"
          >
            <view class="search-box__icon">
              <TnIcon name="search" />
            </view>
            <view class="search-box__tips">搜索动态</view>
          </view>
        </view>
      </TnNavbar>
      // #ifdef MP-WEIXIN
      <AddMiniprogram />
      // #endif
      <!-- 顶部轮播图 -->
      <view class="top-swiper">
        <TnSwiper
          :data="state.swiperData"
          width="100%"
          height="100%"
          indicator
          loop
          autoplay
        >
          <template #default="{ data }">
            <view class="swiper-item" @click="tnNavPage(data.jump_link)">
              <image
                class="tn-image"
                :src="FILE_URL + data.image"
                mode="aspectFill"
              />
            </view>
          </template>
        </TnSwiper>
      </view>

      <!-- 通知 -->
      <view
        v-if="state.noticeBar.length > 0"
        :id="triggerElementId"
        class="notice-container"
      >
        <view class="notice-info">
          <view class="icon">
            <image src="@/static/images/notice.png" mode="aspectFit" />
          </view>
          <view class="tn-text-ellipsis-1">
            <TnNoticeBar
              text-color="tn-orange"
              bg-color="tn-type-warning_bg"
              :data="state.noticeBar"
              direction="vertical"
              loop
              @click="clickNotice"
            />
          </view>
        </view>
        <tn-modal ref="modalRef" />
      </view>
      <view style="border-bottom: 20rpx solid var(--tn-color-gray-light)" />

      <!-- 页面内容 -->
      <view class="sub-page-container">
        <view class="nav-title">
          <view class="left">
            <TnTitle
              title="圈子分类"
              mode="subTitle"
              sub-title="circles-type"
              size="lg"
              class="tn-text-bold"
            />
          </view>
          <view class="right" @tap.stop="tnNavPage('/circlesPages/classify')">
            圈子广场
            <TnIcon name="circle-more" />
          </view>
        </view>

        <!-- 导航分类 -->
        <view v-if="state.hotCirclesData.length > 0">
          <TnScrollList :indicator="false">
            <view class="category-container">
              <view
                v-for="(item, index) in state.hotCirclesData"
                :key="index"
                class="category-item"
                @tap.stop="
                  tnNavPage(
                    '/circlesPages/classify?circlesTypeName=' + item.name
                  )
                "
              >
                <view class="item-icon">
                  <image :src="FILE_URL + item.icon" mode="scaleToFill" />
                </view>
                <view class="item-name">{{ item.name }}</view>
              </view>
            </view>
          </TnScrollList>
        </view>
        <view v-else class="tn-pb">
          <TnEmpty mode="data" color="#e6e6e6" />
        </view>
        <view style="border-bottom: 20rpx solid var(--tn-color-gray-light)" />

        <!-- 发现好友 -->
        <view class="find-friends">
          <view class="ff-title">
            <TnTitle
              title="发现好友"
              mode="subTitle"
              sub-title="find-friends"
              size="lg"
              class="tn-text-bold"
            />
          </view>
          <view class="content-wrapper">
            <view
              class="content-item tn-shadow-blur tn-gradient-bg__blue"
              @tap.stop="tnNavPage('/friendPages/schoolmate')"
            >
              <view class="left">
                <view class="title">找同学</view>
                <view class="show-more">
                  <text>同窗识</text>
                  <TnIcon name="right" />
                </view>
              </view>
              <view class="icon">
                <TnIcon name="education" />
              </view>
            </view>
            <view
              class="content-item tn-shadow-blur tn-gradient-bg__orange"
              @tap.stop="tnNavPage('/friendPages/homie')"
            >
              <view class="left">
                <view class="title">找老乡</view>
                <view class="show-more">
                  <text>故土情</text>
                  <TnIcon name="right" />
                </view>
              </view>
              <view class="icon">
                <TnIcon name="my-love" />
              </view>
            </view>
            <view
              class="content-item tn-shadow-blur tn-gradient-bg__bluepurple"
              @tap.stop="tnNavPage('/friendPages/sameindustry')"
            >
              <view class="left">
                <view class="title">找同行</view>
                <view class="show-more">
                  <text>业界友</text>
                  <TnIcon name="right" />
                </view>
              </view>
              <view class="icon">
                <TnIcon name="team-fill" />
              </view>
            </view>
          </view>
        </view>
        <view style="border-bottom: 20rpx solid var(--tn-color-gray-light)" />

        <!-- 新闻资讯 -->
        <view class="newest">
          <view class="nav-title">
            <view class="left">
              <TnTitle
                title="最新资讯"
                mode="subTitle"
                sub-title="newest"
                size="lg"
                class="tn-text-bold"
              />
            </view>
            <view class="right" @tap.stop="tnNavPage('/articlePages/index')">
              更多
              <TnIcon name="fire" />
            </view>
          </view>
          <view v-if="state.articleLists.length > 0" class="newest-list">
            <view class="list-item">
              <view
                v-for="(item, index) in state.articleLists"
                :key="index"
                class="top"
                @tap.stop="navArticleDetail(item.id)"
              >
                <view class="list-info">
                  <view class="icon">
                    <TnIcon name="hotspot" size="45" />
                  </view>
                  <view class="tn-text-ellipsis-1">{{ item.title }}</view>
                </view>
                <view class="list-operation"> {{ item.update_date }} </view>
              </view>
            </view>
          </view>
          <view v-else class="tn-pb">
            <TnEmpty mode="data" color="#e6e6e6" />
          </view>
        </view>
      </view>
      <view style="border-bottom: 20rpx solid var(--tn-color-gray-light)" />

      <TnSticky
        :id="triggerElementId"
        :offset-top="navBarInfo.height"
        :z-index="19030"
        class="tabs-sticky"
      >
        <view class="tabs">
          <TnTabs
            v-model="state.currentTabIndex"
            font-size="34"
            active-font-size="40"
            active-color="#080808"
            color="#7d7d7d"
            :bottom-shadow="false"
            :scroll="false"
          >
            <TnTabsItem
              v-for="(item, index) in state.tabsData"
              :key="index"
              :title="item.text"
              @click="handleCirclesPlateClick(index, item.plate)"
            />

            <template #bar>
              <view class="custom-bar">
                <TnIcon name="tabs-smile" />
              </view>
            </template>
          </TnTabs>
        </view>
      </TnSticky>

      <z-paging
        ref="paging"
        v-model="state.circlesPostLists"
        use-page-scroll
        @query="queryList"
      >
        <template #refresher="{ refresherStatus }">
          <CustomRefresher :status="refresherStatus" />
        </template>
        <!-- 动态列表 -->
        <view class="dynamic-list">
          <view
            v-for="(item, index) in state.circlesPostLists"
            :key="index"
            class="dynamic"
          >
            <view v-if="state.circlesPostLists.length > 0" class="graphic-card">
              <!-- 简要信息 -->
              <view class="brief-info">
                <view class="brief-info__content">
                  <view class="brief-info__avatar">
                    <image
                      class="circles-image"
                      :src="FILE_URL + item.circles.image"
                      mode="aspectFill"
                    />
                  </view>
                  <view class="brief-info__data">
                    <TnButton
                      bg-color="rgba(1, 190, 255, 0.1)"
                      text-color="tn-type-primary"
                      font-size="22rpx"
                      :custom-style="{
                        borderRadius: '10rpx',
                      }"
                      @click="navCirclesDetailPage(item.circles.id)"
                    >
                      <TnIcon name="circle-more" />
                      {{ item.circles.name }}
                    </TnButton>
                    <view
                      class="desc tn-text-ellipsis-1"
                      @click="navUserHomePage(item.user.id)"
                    >
                      <TnAvatar
                        size="30"
                        :border="true"
                        :url="FILE_URL + item.user.avatar"
                      />
                      <span class="username">
                        {{ item.user.nickname }}
                        <span class="tn-gray-disabled user-release">
                          发布
                        </span>
                      </span>
                    </view>
                  </view>
                </view>
                <view class="brief-info__operation">
                  <slot name="briefOperation">
                    <view class="brief-info__operation">
                      <!-- <TnIcon name="group-square" /> -->
                    </view>
                  </slot>
                </view>
              </view>
              <!-- 内容容器 -->
              <view class="container">
                <!-- 内容 -->
                <view class="content tn-text-ellipsis-5">
                  <!-- 标签和内容 -->
                  <view class="content__tags">
                    <view
                      v-for="(tagItem, tagIndex) in item.topics_name"
                      :key="tagIndex"
                      class="tag-item"
                    >
                      <text @click="navTopicDetailPage(tagItem)">
                        #{{ tagItem }}
                      </text>
                    </view>
                  </view>
                  <view
                    class="content__data"
                    @tap.stop="navCirclesPostDetailPage(item.id)"
                  >
                    <text>{{ item.content }}</text>
                  </view>
                </view>
                <!-- 图片列表 -->
                <view
                  v-if="item.attachment_type == 'image'"
                  class="images"
                  @tap.stop="navCirclesPostDetailPage(item.id)"
                >
                  <!-- 一张图片 -->
                  <view v-if="item.attachment.length === 1" class="images-one">
                    <TnLazyLoad :src="item.attachment[0]" />
                  </view>
                  <!-- 两张图片 -->
                  <view v-if="item.attachment.length === 2" class="images-two">
                    <TnPhotoAlbum :data="item.attachment" :column="2" />
                  </view>
                  <!-- 三张图片 -->
                  <view
                    v-if="item.attachment.length === 3"
                    class="images-three"
                  >
                    <view class="image-wrapper-left">
                      <view class="image-container">
                        <TnLazyLoad :src="item.attachment[0]" />
                      </view>
                    </view>
                    <view class="image-wrapper-right">
                      <view class="image-container">
                        <TnLazyLoad :src="item.attachment[1]" />
                      </view>
                      <view class="image-container">
                        <TnLazyLoad :src="item.attachment[2]" />
                      </view>
                    </view>
                  </view>
                  <!-- 四张图片 -->
                  <view v-if="item.attachment.length === 4" class="images-four">
                    <TnPhotoAlbum :data="item.attachment" :column="2" />
                  </view>
                  <TnPhotoAlbum
                    v-if="item.attachment.length >= 5"
                    :data="item.attachment"
                  />
                </view>

                <!-- 视频 -->
                <view
                  v-if="item.attachment_type == 'video'"
                  class="content-video"
                  @click="navVideoLists(item.id)"
                >
                  <view class="video-icon">
                    <TnIcon name="video-fill" size="100" color="#FFFFFF" />
                  </view>
                  <video
                    class="video-data"
                    :src="FILE_URL + item.attachment"
                    :muted="true"
                    object-fit="cover"
                    :enable-progress-gesture="false"
                    :show-loading="false"
                    :show-play-btn="false"
                    :show-center-play-btn="false"
                    :show-fullscreen-btn="false"
                    :controls="false"
                    :autoplay="false"
                    :enable-play-gesture="false"
                    :loop="true"
                  />
                </view>

                <!-- 语音 -->
                <view v-if="item.attachment_type == 'voice'" class="audio">
                  <luch-audio
                    :play.sync="true"
                    :name="item.user.nickname"
                    author="录制"
                    :poster="FILE_URL + item.user.avatar"
                    :src="FILE_URL + item.attachment"
                    :autoplay="false"
                  />
                </view>
              </view>

              <!-- 链接 -->
              <view v-if="item.attachment_type == 'link'" class="link">
                <uni-link
                  :href="item.attachment"
                  :text="item.attachment"
                  color="#007BFF"
                  copy-tips="链接已复制"
                  font-size="18"
                />
              </view>

              <!-- 底部信息 -->
              <view v-if="item.location !== ''" class="location-info">
                <TnButton
                  plain
                  border-color="tn-grey-disabled"
                  custom-class="custom-button-class"
                  @click="
                    jumpMap(
                      item.longitude,
                      item.latitude,
                      item.location,
                      item.poiaddress
                    )
                  "
                >
                  <TnIcon name="location-fill" color="tn-blue" />
                  <view class="location-name">{{ item.location }}</view>
                </TnButton>
              </view>
              <view class="bottom-info">
                <view class="bottom-info__left">
                  <!-- 底部左侧数据 -->
                  <view class="desc tn-text-ellipsis-1">
                    {{ item.update_date }}
                  </view>
                </view>
                <view class="bottom-info__right">
                  <!-- 底部右侧数据 -->
                  <view class="count-item-data">
                    <TnIcon name="eye" />
                    <view class="count">{{ item.view_total }}</view>
                  </view>
                  <view class="count-item-data">
                    <TnIcon name="message" />
                    <view class="count"> {{ item.comment_total }} </view>
                  </view>
                  <view v-if="item.plate == 'dynamic'" class="count-item-data">
                    <TnIcon name="like" />
                    <view class="count">{{ item.like_total }}</view>
                  </view>
                </view>
              </view>
            </view>
            <view
              style="border-bottom: 20rpx solid var(--tn-color-gray-light)"
            />
          </view>
        </view>
      </z-paging>
    </view>
  </PageContainer>
</template>

<style lang="scss" scoped>
@use '@/static/css/home.scss';
@use '@/static/css/graphic-card.scss';
</style>
